import time
from django.core.cache import cache
from django.http import HttpResponse
from elasticsearch import Elasticsearch
from redis import StrictRedis


class DePaMiddleware:
    """黑名单过滤中间件"""
    es = Elasticsearch([{'host': '121.4.140.74', 'port': 9200}], timeout=3600)
    # redis = StrictRedis(host='121.4.140.74', port=2333, db=1, password='snbzsyc', decode_responses=True)

    def __init__(self, get_response=None):
        self.get_response = get_response
        super().__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

    def process_request(self, request, *args, **kwargs):
        ip = request.META.get("REMOTE_ADDR")
        black_list = cache.get("blackList", [])
        uri = request.META.get("PATH_INFO")
        if ip in black_list and uri != "/clearcache/":
            return HttpResponse('<h1>403 Forbidden</h1>', status=403)
        else:
            self.insert_ES(ip, request)
        requests = cache.get(ip, [])
        while requests and time.time() - requests[-1] > 60:
            requests.pop()
        requests.insert(0, time.time())
        cache.set(ip, requests, timeout=60)
        if len(requests) > 13:
            black_list.append(ip)
            cache.set("blackList", black_list, timeout=60 * 60 * 24)
            return HttpResponse('<h1>403 Forbidden</h1>', status=403)
    # def process_response(self, request, response):
    #     ip = request.META.get("REMOTE_ADDR")
    #     count = self.redis.get(ip)
    #     if count:
    #         count = int(count) - 1
    #         if count == 0:
    #             self.redis.delete(ip)
    #             print(ip + " delete")
    #         else:
    #             print(ip + " count -1")
    #             self.redis.set(ip, count)
    #     return HttpResponse(response, status=response.status_code)

    def process_exception(self, request, exception):
        """视图函数出现异常, 会调用这个函数"""
        print(exception)
        print('exception')

    def insert_ES(self, ip, request):
        if ip != "ip=1.15.178.69":
            action = {
                "ip": ip,
                "uri": request.META.get("PATH_INFO"),
                "@timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                "timestamp": int(round(time.time() * 1000)),
            }
            self.es.index(index="index_a", doc_type="doc_type_test", body=action)
